﻿define(['localResize','slip','configModule','reqErrCode-module','httpService-module'],function(){
	angular.module("utilModule", ['localResizeIMG','ConfigModule','ReqErrorCodeModule','HttpServicesModule'])
	.service("layer", function (errorServices,$timeout,$rootScope,$http,SystemConfig,$location) {		
		
		var self = this;	
		//屏幕宽度
		var w_width = $(window).width();
		//当前div最大宽度
		var d_maxWidth = $("div").width();
		//屏幕高度
		var w_height =  $(window).height();
		
		/**
		 * div层动态计算比例
		 * u_width: width比例
		 * */
		var divCount = function(u_width) {
			
			if(angular.isUndefined(u_width)) {
				u_width = 0.8;
			}
			
			var s_width = (w_width -  d_maxWidth) / 2;	//用于遮罩层
			var d_width = 0;							//普通层
			var c_width = 0;							//取消层
			var max_width = d_maxWidth;					//普通层当前最大宽度
			
			if(w_width > d_maxWidth) {
				d_width = (w_width - d_maxWidth) / 2;
				if(w_width*u_width > d_maxWidth-200) {
					max_width = d_maxWidth*u_width;
					d_width += (d_maxWidth - max_width) / 2;
				}
				c_width = d_width + d_maxWidth*u_width - 20;
			} else {
				d_width = (w_width - d_maxWidth * u_width) / 2;
				c_width = d_width + d_maxWidth*u_width - 20;
			}
			
			return {
				s_width 	: s_width,
				d_width 	: d_width,
				c_width		: c_width,
				max_width	: max_width
			}
		}
		
		/**
		 * 阻止事件冒泡,防止事件穿透
		 * */
		var preventEvent = function() {
			var oevent = window.event||arguments[0];
			//阻止触摸时的缩放、滚动条滚动
			oevent.preventDefault();
		}
		
		/**
			提示信息框
			_msg: 提示信息内容
		*/
		self.show = function(_msg) {
			if(angular.isObject(_msg)) {
				_msg = errorServices.msg(_msg);
			}
			if(angular.isUndefined($("#l-hintShow").html())) {			
				var s_width = divCount().s_width;
				
				var style = "width:100%;text-align:center;padding:12px 0px;background:black;opacity:0.8;color:#fff;position: fixed;top:0;left:"+s_width+"px;z-index:9999;";
				var div = $("<div id='l-hintShow' style='"+style+"'>"+_msg+"</div>");
				div.appendTo($("body")).fadeIn("slow");
				$timeout(function(){
					$("#l-hintShow").fadeOut("slow",function(){
						$("#l-hintShow").remove();
					});
				},2500)
			} 			
		}	
		
		/**
			确认框提示框
			_msg: 提示内容
			_func: 确定按钮回调事件
			_func1: 取消按钮回调事件
		*/
		self.confirm = function (_msg, _func, _func1) {
			preventEvent();
			if(angular.isUndefined($("#l-confirm").html())) {
				var s_width = divCount(0.9).s_width;
				var d_width = divCount(0.9).d_width;
				var max_width = divCount(0.9).max_width;			
				
				var warp = "width: 90%;background:#fff;position:fixed;z-index:9999;top:30%;left:"+d_width+"px;max-width:"+max_width+"px;text-align:initial;border-radius:7px;border:1px solid #D9D9D9;";
				var msg =   "word-break:break-word;overflow:hidden;padding: 12% 15px 16% 15px;border-bottom:1px solid #D9D9D9;border-radius:7px 7px 0 0;text-align: center;";
				var canel = "color:#0075ff;float:left;width:50%;padding: 15px 0px;text-align:center;border-right:1px solid #D9D9D9;-webkit-box-sizing:border-box;";
				var queding="float:right;width:50%;padding: 15px 0px;text-align:center;color:#0075ff;";
				var height = $(window).height();
				
				//遮罩层
				var shade = $("<div id='l-shade' style='width:100%;height:"+height+"px;background:black;position:fixed;opacity:0.6;z-index:9998;top:0;left:"+s_width+"px;'></div>");
				var div = $("<div id='l-confirm' style='"+warp+"'>" +
								"<div style='"+msg+"' id='l-congrim-msg'>"+_msg+"</div>" +
								"<div style='"+canel+"' id='l-canel'>取     消</div>" +			
								"<div style='"+queding+"' id='l-queding'>好</div>" +
							"</div>");
			
				shade.appendTo($("#ng-view"));
				div.appendTo($("#ng-view")).fadeIn("slow");	
				
				$("#l-queding").bind('click',function(){
					$("#l-shade").remove();
					$("#l-confirm").remove();
					if(angular.isFunction(_func)){
						_func();
					}
					preventEvent();
				});
				$("#l-canel").bind('click',function(){	
					$("#l-shade").remove();
					$("#l-confirm").remove();
					if(angular.isFunction(_func1)){
						_func1();
					}				
					preventEvent();
				});			
			} 			
		};
		
		/**
		 * 将div变成弹出层
		 * divId: 要变成弹出层的div
		 * height: undefined为屏幕高度，0为等宽
		 * */
		self.popup = function(divId,height) {
			preventEvent();
			
			var s_width = divCount().s_width;
			var d_width = divCount(0.9).d_width;
			var c_width = divCount(0.9).c_width;
			var max_width = divCount(0.9).max_width;
			//弹出层高度
			var divHeight = w_height;
			if(!angular.isUndefined(height)) {
				divHeight = height;
				if(height == 0){
					divHeight = (max_width + 100) * 0.93;
				}
			}
			
			var warp = "width: 90%;max-width:"+max_width+"px;height:"+(divHeight-100)+"px;background:#fff;color:#32A4E6;position:fixed;z-index:9999;top:0;left:"+d_width+"px;" +
			"margin-top: 40px;border-radius:7px;overflow:auto;-webkit-overflow-scrolling:touch;-moz-overflow-scrolling:touch;-o-overflow-scrolling:touch;overflow-scrolling:touch;";
			$("#"+divId).attr('style',warp).fadeIn('slow');
			
			var canel = $("<div id='embs_canel' style='font-size:20px;cursor: pointer;background:#ccc;color:#fff;border-radius:50%;width:25px;height:25px;line-height:20px;text-align:center;position:fixed;z-index:10000;top:22px;left:"+c_width+"px;'>x</div>");
			//遮罩层
			var shade = $("<div id='embs_shade' style='width:100%;height:"+w_height+"px;background:black;position:fixed;opacity:0.6;z-index:9998;top:0;left:"+s_width+"px;'></div>");
			shade.appendTo($("#ng-view"));
			canel.appendTo($("#ng-view"));
			$("#embs_canel").bind('click',function(){
				self.closePopup(divId);
				preventEvent();
			});
		}

		
		/**
		 * 关闭弹出层
		 * divId: 要变成弹出层的div
		 * */
		self.closePopup = function(divId) {
			$("#embs_shade").remove();	//删除遮罩层
			$("#embs_canel").remove();	//删除弹出层
			$('#'+divId).fadeOut('slow');
		};
		
		/**
		 * 输入框
		 * _backfunc: 确定按钮回调事件
		 * */
		self.import = function(_backfunc) {
			preventEvent();
			var s_width = divCount(0.9).s_width;
			var d_width = divCount(0.9).d_width;
			var max_width = divCount(0.9).max_width;
			
			var d_height = d_width * 0.8 + 175;
			if(d_maxWidth * 0.8 == max_width) {
				d_height = max_width * 0.35;
			}
			
			var warp = "width: 90%;background:#fff;position:fixed;z-index:9999;top:25%;left:"+d_width+"px;max-width:"+max_width+"px;text-align:initial;border-radius:7px;border:1px solid #D9D9D9;";
			var msg =   "word-break:break-word;overflow:hidden;border-bottom:1px solid #D9D9D9;border-radius:7px 7px 0 0;";
			var canel = "color:#6AB5FF;float:left;width:50%;padding: 15px 0px;text-align:center;border-right:1px solid #D9D9D9;-webkit-box-sizing:border-box;";
			var queding="float:right;width:50%;padding: 15px 0px;text-align:center;color:#6AB5FF;";
			//遮罩层
			var shade = $("<div style='width:100%;height:"+w_height+"px;background:black;position:fixed;opacity:0.5;z-index:9998;top:0;left:"+s_width+"px;'></div>");
			var div = $("<div style='"+warp+"'>" +
							"<div style='"+msg+"'><textarea style='padding:5px; 0px;width:100%;height:"+(d_height-65)+"px;border:0px;font-size:16px;' id='import_textareas' placeholder='亲，写点什么把！'></textarea></div>" +
							"<div style='"+canel+"' id='canel'>取    消</div><div style='"+queding+"' id='queding'>确    定</div>" +
						"</div>");
			shade.appendTo($("#ng-view"));
			div.appendTo($("#ng-view"));
			$("#canel").bind('click',function(){
				shade.remove();
				div.remove();
				preventEvent();
			});
			$("#queding").bind('click',function(){
				var val = $.trim($("#import_textareas").val());
				if(val == '' || val.length == 0) {
					self.show('内容不能为空!');
				} else {
					_backfunc(val);
					shade.remove();
					div.remove();
				}
				preventEvent();
			});
		};
		
		/**
		 * 聊天框，带上传图片
		 * type:调用请传2,
		 * isImg: 是否需要上传图片按钮：默认需要，不需要请传入任意参数
		 * _cal:确定按钮回调事件
		 * */
		self.comment = function(_cal,type,isImg) {
			//获取配置中上传图片个数
			var imgLength = SystemConfig.getConfig().imgLength;			
			if(type == 1) {
				var s_width = divCount().s_width;
				var d_width = divCount().d_width;
				//遮罩层
				var shade = $("<div id='l-import2-shade' style='display:none;width:100%;height:"+w_height+"px;background:black;position:fixed;opacity:0.5;z-index:9997;top:0;left:"+s_width+"px;'></div>");
				var html = $("<div class='l-g-message_warp'>"+
				//		"<textarea class='l-g-message_textarea' placeholder='写点什么把！' id='import_textarea'></textarea>"+
						"<div id='import_textarea' contenteditable='true' class='l-g-message_textarea'></div>"+
						"<div class='l-g-message_btn'>"+
							"<span class='l-g-message_btn_icon1'><img src='images/forumplate/5.png'></span>"+
							"<l-r-img class='l-g-message_btn_icon2' change='imgChange' success='imgSuccess'></l-r-img>"+
							"<span class='l-g-message_btn_btn1'>发送</span>"+
							"<span class='l-g-message_btn_btn2' id='l-g-message_btn_quxiao'>取消</span>"+
							"<span class='l-g-message_btn_btn2' id='l-g-message_btn_clear'>清空</span>"+
						"</div>"+
						"<div class='l-g-message_imgdiv_warp' id='l-camera-div'>"+		
							"<div id='l-camera-imgdiv'></div>"+
							"<p class='l-g-message_img_divwarp_desc'>亲，您还可以上传<span id='l-camera-length'>"+imgLength+"</span>张图片哟。</p>"+
						"</div>"+
						"<div class='l-g-message_qqfacediv_warp'>"+
							"<ul id='g_change_screen_ul'>"+
								"<li class='g_change_screen_ul_li' id='g_change_screen_ul_li1'></li>"+
								"<li class='g_change_screen_ul_li' id='g_change_screen_ul_li2'></li>"+
								"<li class='g_change_screen_ul_li' id='g_change_screen_ul_li3'></li>"+
							"</ul>"+
						"</div>"+
						"<div class='g_slider_status'>"+
						    "<span class='g_slider_status1'></span>"+
						    "<span class='g_slider_status2'></span>"+
						    "<span class='g_slider_status2'></span>"+
						"</div>"+
					"</div>");
				html.appendTo($(document.body));
				shade.appendTo($(document.body));
				$("#g_change_screen_ul").width(w_width*0.96 * 3);	
				//显示QQ表情
				$('.l-g-message_btn_icon1').qqFace({
					id : 'facebox', 
					assign:'import_textarea',		//输入框id
					path:'/wap/images/arclist/'	//表情存放的路径
				});	
				
				$(".l-g-message_btn_icon1").bind("click",function(){
					$(".l-g-message_qqfacediv_warp").show();
					$(".g_slider_status").show();
					$(".l-g-message_imgdiv_warp").hide();
					
					//表情滚动
					slip('page',g_change_screen_ul,{
						num: 3,
						endFun: function(){
							$(".g_slider_status span").each(function(i){
								$(this).removeClass('g_slider_status1').addClass('g_slider_status2');
							})
							$(".g_slider_status span").eq(this.page).removeClass('g_slider_status2').addClass('g_slider_status1');
						}
					});					
				});	
				//此处理让用户一点击表情按钮时所有表情已加载完毕显示。保证全部表情已显示。
				$(".l-g-message_btn_icon1").click();
				$(".l-g-message_qqfacediv_warp").hide();
				$(".g_slider_status").hide();
				
				//清空按钮
				$("#l-g-message_btn_clear").bind('click',function(){
					$("#import_textarea").html('');
				});
				
				//取消按钮
				$("#l-g-message_btn_quxiao").bind("click",function(){
					$(".l-g-message_warp").hide();
					shade.hide();
					preventEvent();
				});			
				//上传图片按钮点击事件
				$(".l-g-message_btn_icon2").bind('click',function(){
					if($("#l-camera-imgdiv").children().length > 0 && angular.isUndefined(isImg)) {
						$("#l-camera-div").show();
						$(".l-g-message_qqfacediv_warp").hide();
						$(".g_slider_status").hide();
					}
				});
				var div;	//图片层
				var isUpload = true; //是否上传
				$rootScope.rootScope_imgArray = [];
				
				//正在压缩
				$rootScope.imgChange = function() {
					$(".l-g-message_qqfacediv_warp").hide();
					$(".g_slider_status").hide();
					var l_camera_length = imgLength-$(".l-g-message_img_divwarp").length;
					if(l_camera_length == 0) {				
						self.show('亲，您已上传'+imgLength+'张图片了哟!');
						isUpload = false;
						return;
					}
					$("#l-camera-length").text(l_camera_length-1);
					div = $("<div class='l-g-message_img_divwarp'>"+
									"<span class='icon-trash l-g-message_img_divwarp_removebtn' ></span>"+
									"<img src='images/global/imgloading.gif' />"+
								"</div>");
					div.appendTo($("#l-camera-imgdiv"));			
					$("#l-camera-div").show();
					$(".l-g-message_img_divwarp_removebtn").bind("click",function(){
						var index = $(".l-g-message_img_divwarp").index($(this).parent());
						$rootScope.rootScope_imgArray.splice(index,1);
						$(this).parent().remove();				
						l_camera_length++;
						$("#l-camera-length").text(l_camera_length-1);
					});
				}
				//压缩成功
				$rootScope.imgSuccess = function (stop, data) {
					if(isUpload) {
						$rootScope.$apply();
						stop();
						//将base64格式的图片上传			
						$.ajax({
							'type'		: 'post',
							'url'		: '/eimp/fodder/upMobilePicture',
							'data'		: {'picture': data.base64Clean},
							'datatype'	: 'json',
							'async'		: true,
							'success'	: function(d) {							
								var url = d.urlprefix + d.filename;
								$(div).find('img').attr('src',url);
								$rootScope.rootScope_imgArray.push('[img:' + url + ']');
							}
						});
					}
				}	
			} else {
				//隐藏图片上传按钮及图片层
				if(!angular.isUndefined(isImg)) {
					$(".l-g-message_btn_icon2").hide();
					$("#l-camera-div").hide();
				} else {
					$(".l-g-message_btn_icon2").show();
				}
				$(".l-g-message_warp").show();
				$("#l-import2-shade").show();
				$(".l-g-message_btn_btn1").unbind('click');
				$(".l-g-message_btn_btn1").bind("click",function(){
					var val = $.trim($("#import_textarea").html());
					if(angular.isUndefined(isImg)) {
						if((val == '' || val.length == 0) && $rootScope.rootScope_imgArray.length == 0) {
							self.show('请写点什么把!亲');
							return;
						} 
						if($rootScope.rootScope_imgArray.length > 0) {
							val = val  + '_${Leon}_' + $rootScope.rootScope_imgArray.toString();
						}
					} else {
						if(val == '' || val.length == 0) {
							self.show('请写点什么把!亲');
							return;
						} 
					}
					_cal(val);
					$rootScope.rootScope_imgArray = [];
					$("#l-camera-imgdiv").html('');
					$("#import_textarea").html('');
					$("#l-camera-div").hide();
					$(".l-g-message_warp").hide();
					$("#l-import2-shade").hide();
					$(".l-g-message_qqfacediv_warp").hide();
					$(".g_slider_status").hide();
					preventEvent();
				});
			}
		}
		//self.comment(undefined,1);
		
		/**
		*	加载层 
		*	_msg: 传入'close'关闭加载
		*/
		self.progress = function(_msg) {
			var d_width = 0;							//普通层
			if(w_width > d_maxWidth) {
				d_width = (w_width - d_maxWidth) / 2;
				if(w_width*0.8 > d_maxWidth-200) {
					d_width += (d_maxWidth - d_maxWidth * 0.8 * 0.77) / 2;
				}
			} else {
				d_width = (w_width - d_maxWidth * 0.50) / 2;
			}
			if(angular.isUndefined(_msg)) {
				if(angular.isUndefined($("#l-progress").html())) {
					var div = $("<div id='l-progress' style='position: fixed;width:80%;top:40%;left:"+(d_width+5)+"px;display:none;z-index:9999;'>" +
									"<img src='images/global/loading.gif' style='width:60%;' />" +
								"</div>");
					div.appendTo($("body")).fadeIn("slow");
				} else {
					if($("#l-progress").css('display') == 'none') {
						$("#l-progress").fadeIn("slow");
					}
				}	
			} else {
				$("#l-progress").fadeOut("fast");
			}		
		}
		
		/**
		 * 查询输入框
		 * _callback: 查询回调事件
		 * */
		self.search = function(_callback) {
			if(angular.isUndefined(placeholder)) {
				placeholder = '';
			}
			if(angular.isUndefined($("#l-search").html())) {			
				var s_width = divCount().s_width;
				var style = "width:100%;padding:10px 0px;background:#EEEEEE;position: fixed;bottom:0;left:"+s_width+"px;z-index:9998;";
				var span = "color:#fff;border-radius:7px;padding:5px;background:#769cdc;margin-left:10px;"
				var div = $("<div id='l-search' style='"+style+"'>" +
								"<input placeholder="+placeholder+" id='l-search-input' style='padding: 9px 4px;width:50%;margin-left:2%;border:1px solid #769cdc;font-size:16px;' />" +
								"<span style='"+span+"' id='l-search-btn'>" +
									"<span class='icon-zoom-out'></span><span'> 查询</span>" +
								"</span>" +
								"<span style='"+span+"' id='l-canel-btn'>" +
									"<span class='icon-remove'></span><span> 取消</span>" +
								"</span>" +
							"</div>");
				div.appendTo($("#ng-view"));
				$("#l-canel-btn").bind('click',function(){
					div.remove();
					preventEvent();
				});
				$("#l-search-btn").bind('click',function(){
					var val = $.trim($("#l-search-input").val());
					if(val == '' || val.length == 0) {
						self.show('搜索内容不能为空!');
					} else {
						_callback(val);
						div.remove();						
					}
					preventEvent();
				});
			} 					
		}
		
		/**
		 * 滚动条事件
		 * _callback: 下拉加载
		 * _callback2: 上拉刷新
		 * */
		self.scroll = function(_callback,_callback2) {
			$(window).bind('scroll', function() {						
	            if($(window).scrollTop() + $(window).height() >= $(document).height()) {
					_callback();
				} else if($(window).scrollTop() <= 0) {
					if(angular.isFunction(_callback2)) {
						_callback2();		
					}
				}
	        });
		};
		
		/**
		 * 微信图片查看器
		 * current: 	当前图片索引
		 * imglist:		图片src集合
		 * */
		self.imagePreview = function(current, imglist) {	
			wx.previewImage({
	            current: current, // 当前显示的图片链接
	            urls: imglist // 需要预览的图片链接列表
	        });
		}
		
		/**
		 * 微信配置
		 * */
		self.wxConfig = function(obj) {
			wx.config({
			    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
			    appId: obj.appId, // 必填，公众号的唯一标识
			    timestamp: obj.timestamp, // 必填，生成签名的时间戳
			    nonceStr: obj.noncestr, // 必填，生成签名的随机串
			    signature: obj.signature,// 必填，签名，见附录1
			    jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','startRecord','stopRecord','onVoiceRecordEnd','playVoice','pauseVoice',
			                'stopVoice','onVoicePlayEnd','uploadVoice','downloadVoice','chooseImage','previewImage','uploadImage','downloadImage','translateVoice',
			                'getNetworkType','openLocation','getLocation','hideOptionMenu','showOptionMenu','hideMenuItems','showMenuItems','hideAllNonBaseMenuItem',
			                'showAllNonBaseMenuItem','closeWindow','scanQRCode','chooseWXPay','openProductSpecificView','addCard','chooseCard','openCard'
			               ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
			});
		}
		
		/**
		 * 截取访问地址栏后的参数
		 * */
		self.getParameters = function(link) { 
			var url = link.split('#')[1].split('?')[1];
			if(url.indexOf("code=") == -1){
				url = url + "&" + link.split("#")[0].split("?")[1];
			}
			return angular.parseKeyValue(url);
		}
		
		/**
		* 自定义分享参数
		* paramsArray 参数数组：格式[{'key':'tdcode','value':$scope.tdcode},{'key':'leon','value':"leon"}]
		*/
		self.newLink = function(paramsArray) {
			var link = location.href;
			var obj = self.getParameters(link);
			if(link.split('#')[1].indexOf('?') != -1) {
				if(angular.isUndefined(obj.channel)) {
					link = link + '&' + 'channel=' + sessionStorage.getItem('channel');
				}
			} else {
				if(angular.isUndefined(obj.channel)) {
					link = link + '?' + 'channel=' + sessionStorage.getItem('channel');
				}
			}				
			for(var i = 0; i < paramsArray.length; i++) {								
				if(angular.isUndefined(obj[paramsArray[i].key])) {
					link = link + '&' + ""+paramsArray[i].key+"=" + paramsArray[i].value;	
				}			
			}
			if(link.indexOf("&code") != -1 && link.indexOf('&state') != -1) {
				link = link.slice(0, link.indexOf("&code"));
			}

			var str = "https://open.weixin.qq.com/connect/oauth2/authorize?";
			str += "appid=" + sessionStorage.getItem('appid') + "&";
			str += "redirect_uri=" + encodeURIComponent(link) + "&";
			str += "response_type=code&";
			str += "scope=snsapi_base&";
			str += "state=STATE";
			str += "#wechat_redirect";
			return str;
		}

		
		/**
		 * 微信分享设置
		 * options:{}对象类型,属性有如下
		 * title: 设置分享标题
		 * desc:  设置分享描述
		 * link:  设置分享跳转地址
		 * imgurl:设置分享图片
		 * _successCallbackTimeline: 分享到朋友圈成功回调
		 * _errorCallbackTimeline:   分享到朋友圈失败回调
		 * _successCallbackAppMessage: 分享给朋友成功回调
		 * _errorCallbackAppMessage:   分享给朋友失败回调
		 * */
		self.share = function(options, _successCallbackTimeline, _errorCallbackTimeline, _successCallbackAppMessage, _errorCallbackAppMessage) {
			// 分享到朋友圈
			wx.onMenuShareTimeline({
				title: options.title, // 分享标题
				link: options.link, // 分享链接
				imgUrl: options.imgurl, // 分享图标
				success: function () { 
					// 用户确认分享后执行的回调函数
					if(angular.isFunction(_successCallbackTimeline)) {
						_successCallbackTimeline();
					}
				},
				cancel: function () { 
					// 用户取消分享后执行的回调函数
					if(angular.isFunction(_errorCallbackTimeline)) {
						_errorCallbackTimeline();
					}
				}
			});
			// 分享给朋友
			wx.onMenuShareAppMessage({
				title: options.title, // 分享标题
				desc: options.desc, // 分享描述
				link: options.link, // 分享链接
				imgUrl: options.imgurl, // 分享图标
				success: function () { 
					// 用户确认分享后执行的回调函数
					if(angular.isFunction(_successCallbackAppMessage)) {
						_successCallbackAppMessage()
					}
				},
				cancel: function () { 
					// 用户取消分享后执行的回调函数
					if(angular.isFunction(_errorCallbackAppMessage)) {
						_errorCallbackAppMessage();
					}
				}
			});	
		}
		
		/**
		 * 获取用户地理位置
		 * callback
		 * */
		self.getLocation = function(_callback) {
                        var isWeiXin = function (){
			    var ua = window.navigator.userAgent.toLowerCase();
			    if(ua.match(/MicroMessenger/i) == 'micromessenger'){
			        return true;
			    }else{
			        return false;
			    }
			}
			if(!isWeiXin()){ //navigator.geolocation
				navigator.geolocation.getCurrentPosition(function(position){
					var latitude = position.coords.latitude;
					var longitude = position.coords.longitude;
					$.getJSON("http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x="+longitude+"&y="+latitude+"&callback=?",function(d){							
						var lng = base64decode(d.x);
						var lat = base64decode(d.y);
						var point = new BMap.Point(lng,lat);
						var gc = new BMap.Geocoder();				
						gc.getLocation(point, function(rs){								
						   var addComp = rs.addressComponents;
						   address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
						   var options = {
								latitude	: lat,
								longitude	: lng,
								address		: address,
								province	: addComp.province,
								district	: addComp.district,
								street		: addComp.street,
								city		: addComp.city
						   }
						   _callback(options);
						});	
					});	
				});  	
			} else {
				wx.ready(function(){
					wx.getLocation({
					    success: function (res) {
					        var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
					        var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
					        $.getJSON("http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x="+longitude+"&y="+latitude+"&callback=?",function(d){							
								var lng = base64decode(d.x);
								var lat = base64decode(d.y);
								var point = new BMap.Point(lng,lat);
								var gc = new BMap.Geocoder();				
								gc.getLocation(point, function(rs){								
								   var addComp = rs.addressComponents;
								   address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
								   var options = {
										latitude	: lat,
										longitude	: lng,
										address		: address,
										province	: addComp.province,
										district	: addComp.district,
										street		: addComp.street,
										city		: addComp.city
								   }
								   _callback(options);
								});	
							});	
					    }
					});
				});				
			}
		}
		
		/**
		 * base64解密
		 * */
		function base64decode(str){  
			var base64DecodeChars = new Array(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);  
		    var c1, c2, c3, c4;  
		    var i, len, out;  
		    len = str.length;  
		    i = 0;  
		    out = "";  
		    while (i < len) {  
		        /* c1 */  
		        do {  
		            c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];  
		        }  
		        while (i < len && c1 == -1);  
		        if (c1 == -1)   
		            break;  
		        /* c2 */  
		        do {  
		            c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];  
		        }  
		        while (i < len && c2 == -1);  
		        if (c2 == -1)   
		            break;  
		        out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));  
		        /* c3 */  
		        do {  
		            c3 = str.charCodeAt(i++) & 0xff;  
		            if (c3 == 61)   
		                return out;  
		            c3 = base64DecodeChars[c3];  
		        }  
		        while (i < len && c3 == -1);  
		        if (c3 == -1)   
		            break;  
		        out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));  
		        /* c4 */  
		        do {  
		            c4 = str.charCodeAt(i++) & 0xff;  
		            if (c4 == 61)   
		                return out;  
		            c4 = base64DecodeChars[c4];  
		        }  
		        while (i < len && c4 == -1);  
		        if (c4 == -1)   
		            break;  
		        out += String.fromCharCode(((c3 & 0x03) << 6) | c4);  
		    }  
		    return out;  
		}  
		
		/**
		 * 获取当前域名
		 * */
		self.getDomain = function() {
			var url1 = window.location.protocol;
			var url2 = window.location.host;	
			var url = url1 + "//" + url2;
			return url;
		} 
		
		/**
		 * 将类目转换为链接
		 * */
		self.getMenuList = function(list) {
			var menuList = [];
			for(var i = 0; i < list.length; i++) {
				var menuObj = {};
				var item = list[i];
				menuObj.name = item.name; 
				menuObj.picture = item.picture; 
				switch(item.category) {
					case	0 :		//类
						menuObj.url = '#' + item.template + '?pid=' + item.id + '&title=' + item.name; 
						break;
					case	1 :		//链接
						menuObj.url = item.target.match(/http:\/\/|https:\/\/(.*)/g) == null ? "http://" + item.target :  item.target;
						break;
					case	2 :	//正文
						menuObj.url = '#' + item.template + '?id=' + item.target + '&title=' + item.name;
						break;
					case	3 :  //论坛
						if(typeof item.target === 'undefined' || item.target == '') { //默认选择第一个论坛板块
							menuObj.url = '#' + item.template  + '?title=' + item.name;
						} else {
							menuObj.url = '#' + item.template + '?board=' + item.target + '&title=' + item.name;
						}
						break;
					case	4 :	//线下活动
						if(typeof item.target !== 'undefined') { 
							menuObj.url = "#" + item.template + "?id=" + item.target + '&title=' + item.name;
						} 
						break;
					case	5 :	//销售业绩
						break;
					case	6 :	//投票选项
						menuObj.url = "#" + item.template + "?id=" + item.target + '&title=' + item.name;
						break;
					case	7 :	//抽奖活动
						menuObj.url = "#" + item.template + "?id=" + item.target + '&title=' + item.name;
						break;
					case	8 :	//地理位置
						menuObj.url = "#" + item.template + "?id=" + item.target + '&title=' + item.name;
						break;
					case	9 :	//微商城
						if(typeof item.target !== 'undefined' && item.target != '') {
							menuObj.url = "#" + item.template + "?tid=" + item.target + '&typename=' + item.name + '&title=' + item.name;
						} else {
							menuObj.url = "#" + item.template + '?title=' + item.name;
						}
						break;
					case	10 :	//问卷调查
						menuObj.url = '#' + item.template + '?title=' + item.name;
						break;
					case	11 :	//趣味测试
						menuObj.url = '#' + item.template + '?title=' + item.name;
						break;
					case	12 :	//论坛板块分组
						menuObj.url = '#' + item.template + '?groupId=' + item.target + '&title=' + item.name;
						break;
					case	13 :	//微首页
						menuObj.url = '#' + item.template + "?pid=" + item.id + '&title=' + item.name;
						break;
					case	14 :	//招贤纳士
						menuObj.url = '#' + item.template + '?title=' + item.name;
						break;
					case	15 :	// 秒杀团购
						menuObj.url = '#' + item.template + '?title=' + item.name;
						break;
					case	16 :	//预约服务
						menuObj.url =  '#' + item.template + '?title=' + item.name;
						break;
					case	17 :	//产品展示
						menuObj.url = '#' + item.template + '?title=' + item + '&moduleid=' + item.target;
						break;
					case	18 :	//全民经纪人
						menuObj.url = '#' + item.template + '?title=' + item;
						break;
					case	19 :	//全民经纪人
						menuObj.url = '#' + item.template + '?pid=' + item.id + '&title=' + item.name; 
						break;
					default	   :
						menuObj.url = "#";
						break;
				}
				menuList.push(menuObj);
			}
			return menuList;
		}
		
		/**
		 * 验证用户是否是会员
		 * _callback: 是会员需要做的回调函数
		 * */
		self.isMember = function(_callback) {
			if(SystemConfig.getConfig().isAccounts) {
    			if(angular.isUndefined($rootScope.user.phone) || $rootScope.user.phone == '') {
    				self.show('请先绑定帐号！');
    				$location.url("/personalCenter/accountBind/");
    				return;
    			} 
    		} else {
    			if(angular.isUndefined($rootScope.user.phone) || $rootScope.user.phone == '') {
    				self.show('请先完善个人信息');
					$location.url("/personalCenter/updateUser/?isReturn=true");
					return;
    			}
    		}
			if(angular.isFunction(_callback)) {
				_callback();
			}
		}
		
		/**
		 * $scope:	控制器当前作用于变量
		 * _callback: 有用户信息后执行的回调方法
		 * */
		self.initUser = function($scope,_callback) {
			//监听当前用户对象是否存在。
			if(angular.isUndefined($rootScope.user)){
	    		$scope.$on('event:userinfo-acquire', function(event, next){
	    			if(angular.isFunction(_callback)) {
	    				_callback();
	    			}
	        	});
	    	} else {
	    		if(angular.isFunction(_callback)) {
    				_callback();
    			}
	    	}
		}

		return self;

	})
	.service('channel', function(httpServices,$rootScope,layer,$timeout,$routeParams) {

		var self = this;
		
		//获取用户信息
		self.getUser = function(_params,_successback,_errorback){
			httpServices.ajax(_params,_successback,_errorback, 'get', '/eimp/wechat/weuser/mobile/info/get');
		}
		//获取公众号信息
		self.getInfo = function(_params,_success,_error){
			httpServices.ajax(_params,_success,_error,'get','/eimp/wechat/weuser/session/info');			
		}
		//注册当前渠道
		self.registerChannel = function(_params,_success,_error) {
			httpServices.ajax(_params,_success,_error,'post','/eimp/wechat/weuser/mobile/info/registerChannel');	
		}
		//分页检索当前用户购物车条目
		self.cartQuery = function() {
			//分页检索当前用户购物车条目
			httpServices.ajax({'pagesize':100,'pagenum':1},function(data){
				$rootScope.orderLength = data.items.length;
			}, function(){}, 'get', '/eimp/market/cart/mobile/query');	
		}
		//用户注册(签权完成后用户注册)
		self.registerSession = function(_params,_success,_error) {
			httpServices.ajax(_params,_success,_error,'get','/eimp/wechat/weuser/session/register');	
		}
		//签权
		self.wechatSign = function(isAuth,sid) {
			if(sessionStorage.getItem('isSign') == null) {
				/*腾讯签权*/
				if(isAuth) {	//是否需要验证权限
					if(angular.isUndefined(sid) && sessionStorage.getItem('openid') == null) {	//服务号
						var code = $routeParams.code;
						if(angular.isUndefined(code)) {
							code = layer.getParameters(location.href).code;
						}
						self.registerSession({"code": code},function(d){
							//将用户openid保存，以便后端session中用户失效后再次签权。
							sessionStorage.setItem('openid', d.openid);
							//获取用户信息
							self.getUser(function(data){
								sessionStorage.setItem('isSign', true);
								sessionStorage.setItem('user', JSON.stringify(data));
								$rootScope.user = data;
								$rootScope.$broadcast('event:userinfo-acquire');
								if(!angular.isUndefined(data.id)) {
									self.cartQuery();
								}	
							},function(){
								$rootScope.user = undefined;
								$rootScope.$broadcast('event:userinfo-acquire');
							});
						});						
					} else {   //订阅号
						//服务号后端session失效再次签权
						if(angular.isUndefined(sid) && sessionStorage.getItem('openid') != null) {
							sid = sessionStorage.getItem('openid');
						}
						var params = {
							'code'	: 'CODEABCSDSFESDF',
							'coded' : sid
						};
						self.registerSession(params,function(){
							sessionStorage.setItem('openid', sid);
							//获取用户信息
							self.getUser(function(data){
								sessionStorage.setItem('isSign', true);   
								sessionStorage.setItem('user', JSON.stringify(data));
								$rootScope.user = data;
								$rootScope.$broadcast('event:userinfo-acquire');
								if(!angular.isUndefined(data.id)) {
									self.cartQuery();
								}	
							},function(){
								$rootScope.user = undefined;
								$rootScope.$broadcast('event:userinfo-acquire');
							});	
						});									
					}
				}					
			} else {
				//从session中取出用户信息，然后从后台拉取用户信息同步到当前session中，保证session中的用户信息是最新的
				$rootScope.user = JSON.parse(sessionStorage.getItem('user'));
				//更新用户信息
				self.getUser(function(data){
					$rootScope.user = data;
					sessionStorage.setItem('user', JSON.stringify(data));
					$rootScope.$broadcast('event:userinfo-acquire');
					if(!angular.isUndefined(data.id)) {
						self.cartQuery();
					}	
				});
			}
		}			
		return self;
	})	
	.controller('DragdropController',function($scope,layer,$location,httpServices,$rootScope,$timeout){
		//微商城按钮拖拽控制器
		$scope.init = function() {
			$("#dragdrop_l_shade").css('height',$(window).height()+'px');	
		}			

		//跳转首页
		$scope.iconHome = function() {			
			closeShade();
			$location.url(sessionStorage.getItem('microMartHomeUrl'));
		}	
		//分类
		$scope.classify = function() {
			closeShade();
			$location.url('/microMart/productType/');
		}
		//订单
		$scope.order = function() {
			closeShade();
			$location.url('/microMart/allorder/');
		}
		//购物车
		$scope.shoppingCart = function() {
			closeShade();
			$location.url('/microMart/cart/');
		}
		//个人中心
		$scope.userCenter = function() {
			closeShade();
			$location.url('/personalCenter/home/');
		}
		//查询
		$scope.search = function() {
			closeShade();
			$location.url(sessionStorage.getItem('microMartSeek'));
		}
		//拖拽控制器
		$scope.dropclick = function(){
			var height = $(window).height();
			var shade1 = $("<div id='dragdrop_l_shade1' style='width:100%;height:"+height+"px;background:#fff;position:fixed;opacity:0;z-index:9997;top:0;left:0;'></div>");
			shade1.appendTo($("#ng-view"));
			$("#dragdrop_l_shade1").click(function(){
				$(this).remove();
				$("#dragdrop_l_shade").toggle(400,function(){
					$(this).hide();
				});
				$(".g-dragdrop").show();
			});
			$("#dragdrop_l_shade").toggle(400);
		}
		//关闭
		var closeShade = function() {
			$("#dragdrop_l_shade").toggle(400);
			$("#dragdrop_l_shade1").remove();
		}
	})
	
});

